// HTTP 请求配置
function getApiBaseUrl(): string {
  // 检查是否有环境变量配置
  if (import.meta.env.VITE_API_BASE_URL !== undefined) {
    const envUrl = import.meta.env.VITE_API_BASE_URL.trim()
    console.log('🔧 使用环境变量 API URL:', envUrl || '(空字符串 - 使用相对路径)')
    return envUrl
  }
  
  // 根据当前域名自动判断
  const currentHost = window.location.origin
  console.log('🌐 当前域名:', currentHost)
  
  // 如果是localhost开发环境
  if (currentHost.includes('localhost') || currentHost.includes('127.0.0.1')) {
    const devUrl = 'http://127.0.0.1:3000'
    console.log('🛠️ 开发环境 API URL:', devUrl)
    return devUrl
  }
  
  // 生产环境，使用相对路径（因为后端路由已有/api前缀）
  console.log('🚀 生产环境使用相对路径')
  return ''
}

const API_BASE_URL = getApiBaseUrl()
console.log('📡 最终 API URL:', API_BASE_URL || '(空字符串 - 相对路径)')

interface ApiResponse<T> {
  success: boolean
  message: string
  data?: T
  error?: string
}

class ApiService {
  private baseURL: string
  private token: string | null = null

  constructor() {
    this.baseURL = API_BASE_URL
    this.token = localStorage.getItem('auth_token')
  }

  // 设置认证token
  setToken(token: string) {
    this.token = token
    localStorage.setItem('auth_token', token)
  }

  // 清除认证token
  clearToken() {
    this.token = null
    localStorage.removeItem('auth_token')
  }

  // 获取请求头
  private getHeaders(): Headers {
    const headers = new Headers({
      'Content-Type': 'application/json'
    })

    if (this.token) {
      headers.append('Authorization', `Bearer ${this.token}`)
    }

    return headers
  }

  // 通用请求方法
  private async request<T>(
    endpoint: string, 
    options: RequestInit = {}
  ): Promise<ApiResponse<T>> {
    try {
      const url = `${this.baseURL}${endpoint}`
      const config: RequestInit = {
        headers: this.getHeaders(),
        ...options
      }

      const response = await fetch(url, config)
      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.message || `HTTP error! status: ${response.status}`)
      }

      return data
    } catch (error) {
      console.error('API请求失败:', error)
      throw error
    }
  }

  // GET 请求
  async get<T>(endpoint: string): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'GET' })
  }

  // POST 请求
  async post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'POST',
      body: data ? JSON.stringify(data) : undefined
    })
  }

  // PUT 请求
  async put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined
    })
  }

  // DELETE 请求
  async delete<T>(endpoint: string): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'DELETE' })
  }

  // 文件上传
  async upload<T>(endpoint: string, file: File): Promise<ApiResponse<T>> {
    try {
      const formData = new FormData()
      formData.append('image', file)

      const headers = new Headers()
      if (this.token) {
        headers.append('Authorization', `Bearer ${this.token}`)
      }

      const response = await fetch(`${this.baseURL}${endpoint}`, {
        method: 'POST',
        headers,
        body: formData
      })

      const data = await response.json()
      
      if (!response.ok) {
        throw new Error(data.message || `上传失败: ${response.status}`)
      }

      return data
    } catch (error) {
      console.error('文件上传失败:', error)
      throw error
    }
  }
}

export const apiService = new ApiService()
export type { ApiResponse }